package thread;

import java.util.ArrayList;

import bean.util.WindowUtil;
import controller.RobotController;

public class AutoMultiWarThread extends Thread implements Runnable {

	private RobotController mainCtrl = null;

	private ArrayList<RobotController> othCtrls = new ArrayList<RobotController>();

	public AutoMultiWarThread() {
		if (WindowUtil.cgWins.size() > 0) {
			mainCtrl = new RobotController(WindowUtil.cgWins.get(0));
			for (int i = 1; i < WindowUtil.cgWins.size(); i++) {
				othCtrls.add(new RobotController(WindowUtil.cgWins.get(i)));
			}
		}
	}

	public void run() {
		singleWarProcess(mainCtrl);
	}

	private void singleWarProcess(RobotController rbCtrl) {
		int oddNumber = 0;

		int lastPosition = -1;
		int lastStatus = -1;

		while (true) {
			if (ThreadToggle.KEEP_RUNNING) {
				int gameStatus = rbCtrl.getGameStatus();

				switch (gameStatus) {
				case RobotController.NORMAL_STATUS:
					rbCtrl.setConnect();
					oddNumber = 1 - oddNumber;

					rbCtrl.delay(200);
					rbCtrl.moveOnMap(RobotController.NO_DIRECTION, true);
					rbCtrl.delay(500);

					if (oddNumber == 0) {
						rbCtrl.moveOnMap(RobotController.LEFT_DIRECTION, true);
					} else {
						rbCtrl.moveOnMap(RobotController.RIGHT_DIRECTION, true);
					}

					rbCtrl.delay(1000);
					break;
				case RobotController.ROLE_WAR_STATUS:
					rbCtrl.roleActionSelect(RobotController.ATK_ACTION);

					lastPosition = hitEverywhere(rbCtrl, gameStatus);
					break;
				case RobotController.PET_WAR_STATUS:
					if (lastPosition != -1) {
						rbCtrl.hitEnemyOnPosition(lastPosition);
					} else {
						hitEverywhere(rbCtrl, gameStatus);
					}

					lastPosition = -1;
					break;
				default:
					if (lastStatus == RobotController.PET_WAR_STATUS) {
						if (rbCtrl != mainCtrl) {
							return;
						}

						for (RobotController othCtrl : othCtrls) {
							singleWarProcess(othCtrl);
						}
					}

					break;
				}

				lastStatus = gameStatus;
			} else {
				lastStatus = -1;

				if (rbCtrl != mainCtrl) {
					return;
				}
			}

			rbCtrl.delay(500);
		}
	}

	private int hitEverywhere(RobotController rbCtrl, int gameStatus) {
		int position = -1;

		for (int i = 0; i < 10; i++) {
			rbCtrl.hitEnemyOnPosition(i);
			if (gameStatus != rbCtrl.getGameStatus()) {
				position = i;
				break;
			}
		}

		return position;
	}
}
